package linc.fun.openai.openai.apikey;

import cn.hutool.extra.spring.SpringUtil;
import com.unfbx.chatgpt.OpenAiStreamClient;
import linc.fun.openai.config.openai.OpenaiConfig;
import linc.fun.openai.enums.ApiTypeEnum;
import linc.fun.openai.util.OkHttpClientUtil;
import lombok.experimental.UtilityClass;
import okhttp3.OkHttpClient;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.Collections;

/**
 * @author linc
 * @date 2023-3-24
 * ApiKey 聊天 Client 构建者
 */
@UtilityClass
public class ApiKeyChatClientBuilder {

    /**
     * 构建 API 流式请求客户端
     *
     * @return OpenAiStreamClient
     */
    public OpenAiStreamClient buildOpenAiStreamClient() {
        OpenaiConfig openaiConfig = SpringUtil.getBean(OpenaiConfig.class);

        OkHttpClient okHttpClient = OkHttpClientUtil.getInstance(ApiTypeEnum.API_KEY, openaiConfig.getTimeoutMs(),
                openaiConfig.getTimeoutMs(), openaiConfig.getTimeoutMs(), getProxy());

        return OpenAiStreamClient.builder()
                .okHttpClient(okHttpClient)
                .apiKey(Collections.singletonList(openaiConfig.getApiKey()))
                .apiHost(openaiConfig.getApiBaseUrl())
                .build();
    }

    /**
     * 获取 Proxy
     *
     * @return Proxy
     */
    private Proxy getProxy() {
        OpenaiConfig openaiConfig = SpringUtil.getBean(OpenaiConfig.class);
        // 国内需要代理
        Proxy proxy = Proxy.NO_PROXY;
        if (openaiConfig.hasHttpProxy()) {
            proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(openaiConfig.getHttpProxyHost(), openaiConfig.getHttpProxyPort()));
        }
        return proxy;
    }
}
